/**
 * 
 */
package com.jiang.test;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Result;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

/**
 * @author Administrator
 *
 */
public class XMLDelete {

	/**
	 * @param args
	 */
	public static void main(String[] args) throws Exception{
		File file = new File("books.xml");
		InputStream is = new FileInputStream(file);
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		DocumentBuilder db = dbf.newDocumentBuilder();
		Document document = db.parse(is);
		NodeList bookList = document.getElementsByTagName("book");
		int len = bookList.getLength();
		for(int i=0;i<len;i++){
			// 查找当前下的具体子节点
			Element bookEle = (Element) bookList.item(i);
			Node priceNode = bookEle.getElementsByTagName("price").item(0);
			bookEle.removeChild(priceNode);
		}
		
		// 2. 使用transform类输出
		TransformerFactory tf = TransformerFactory.newInstance();
		Transformer transformer = tf.newTransformer();
		DOMSource ds = new DOMSource(document);
		//设置编码
		transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
		Result result = new StreamResult(file);
		transformer.transform(ds, result);
	}

}
